<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Service\playlet;

use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\SDK\Sts\V20150401\Sts;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use App\Service\Credential;
use App\Service\Exception;
use App\Service\RedisService;
use App\Service\Sts20150401Client;
use Darabonba\OpenApi\Models\Config;
use Hyperf\Context\ApplicationContext;

class StsService
{
    /**
     * @Inject
     * @var Credential
     */
    private $credential;

    /**
     * @var RedisService
     */
    public  $redisService;

    /**
     * @Inject
     * @var Sts20150401Client
     */
    private $stsClient;

    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }

    public function getStsToken()
    {
        $key = 'oss';
        $stsToken =$this->redisService->hGet($key,'stsToken');
        if($stsToken) {
            return json_decode($stsToken,true);
        }
        try {
            // 运行本代码示例之前，请确保已使用步骤1创建的RAM用户的访问密钥设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            $config = new Config([
//                'accessKeyId' => 'AccessKeySecret',
//                'accessKeySecret' => 'l5UK5A0oceKz0GvDeWPE6xdMcNR5xc',
                                'accessKeyId' => getenv('ALI_OSS_KEY'),
                                'accessKeySecret' => getenv('ALI_OSS_SECRET'),
            ]);
            $config->endpoint = 'sts.cn-shenzhen.aliyuncs.com';
            $client = new Sts($config);

            $assumeRoleRequest = new AssumeRoleRequest([
                // roleArn填写步骤2获取的角色ARN，例如acs:ram::175708322470****:role/ramtest。
                'roleArn' => 'acs:ram::1003792871152981:role/aliyunosstokengeneratorrole',
                // roleSessionName用于自定义角色会话名称，用来区分不同的令牌，例如填写为sessiontest。
                'roleSessionName' => 'sessiontest',
                // durationSeconds用于设置临时访问凭证有效时间单位为秒，最小值为900，最大值以当前角色设定的最大会话时间为准。本示例指定有效时间为3000秒。
                'durationSeconds' => 3600,
                // policy填写自定义权限策略，用于进一步限制STS临时访问凭证的权限。如果不指定Policy，则返回的STS临时访问凭证默认拥有指定角色的所有权限。
                // 临时访问凭证最后获得的权限是步骤4设置的角色权限和该Policy设置权限的交集。
                //      "policy" => ""
            ]);
            $runtime = new RuntimeOptions([]);
            $result = $client->assumeRoleWithOptions($assumeRoleRequest, $runtime);
            $res = $result->body->credentials;
            if(!empty($res)) {
                $this->redisService->hSet($key,'stsToken',json_encode($res));
                $this->redisService->expire($key,1);
            }
            return $res;
        } catch (\Exception $e) {
            printf($e->getMessage() . PHP_EOL);
        }
    }
}
